<?php

/*
+--------------------------------------------------------------------------
|   Invision Power Board
|   =============================================
|   by Matthew Mecham
|   (c) 2001 - 2006 Invision Power Services, Inc.
|   
|   =============================================
|   
|   
+---------------------------------------------------------------------------
|   > $Date: 2007-05-02 17:29:12 -0400 (Wed, 02 May 2007) $
|   > $Revision: 959 $
|   > $Author: BabyWolf $
+---------------------------------------------------------------------------
|
|   > Access the dkm_bank files
|   > Module written by BabyWolf
|   > Date started: 07th February 2009
|
|	> Module Version Number: 1.0.0
|   > DBA Checked: Sat 07 Feb 2009
|   > Quality Checked: Sat 07 Feb. 2009
+--------------------------------------------------------------------------
*/

if (! defined ( 'IN_IPB' )) {
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files.";
	exit ();
}

/*
 * 
 * updated by : hnmtuan
 * 
 * */
 

class bank {
	# Classes
	var $ipsclass;
	
	# Others
        var $common;
	var $output = "";
	var $page_title = "";
	var $nav = array ();
	var $html = "";
	var $cash_field = "";
	var $configs = "";
	var $system_config = array();
	
	
	/*
	 * 
	 * Updated by : hnmtuan
	 * Date : 30/03/2011
	 *  Declare : $acc_hdvnbit to store account information of hdvnbits.org	
	 *                $is_hdvnbit_select to give state information of hdvnbits.org which is selected
	 * 			   $is_maple_select to give state information of maple which is selected ** updated on 31/3/2011
	 * */
	 var $acc_hdvnbit = "";
	 
	 var $is_hdvnbit_select = false;
	 
	 var $is_maple_select = false;
	 
	
	function init() {
				require_once(ROOT_PATH.'system_config.php');
				$this->system_config = $system_config;
	}
	/*-------------------------------------------------------------------------*/
	// Auto run
	/*-------------------------------------------------------------------------*/
	
	function auto_run() {
		
            $this->init();
            //-----------------------------------------
            // Require the HTML and language modules
            //-----------------------------------------
            
            $this->ipsclass->load_language ( 'lang_bank' );
            $this->ipsclass->load_template ( 'skin_bank' );
            
            $this->base_url = $this->ipsclass->base_url . "act=bank";

            $this->cash_field = "field_" . $this->ipsclass->vars ['dkm_cashid'];

            require_once( ROOT_PATH . 'sources/action_public/Common.php' );
            $this->common = new Common();
            $this->common->ipsclass = & $this->ipsclass;
            //-----------------------------------------
            // Check viewing permissions, etc
            //-----------------------------------------

            
            if (! $this->ipsclass->member ['id']) {
                    $this->ipsclass->Error ( array ('LEVEL' => 1, 'MSG' => 'no_guests' ) );
            }

            // Load bank configurations
            
            $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'bank_configs' ) );
            $this->ipsclass->DB->simple_exec ();

            while ( $config = $this->ipsclass->DB->fetch_row () ) {
                    $this->configs [$config ['bank_config_key']] = $config;
            }


            //-----------------------------------------
            // What to do?
            //-----------------------------------------
            //$this->output = $this->ipsclass->compiled_templates ['skin_bank']->menu_bar ();
            $member_id = intval($this->ipsclass->member['id']);
            $member = $this->common->format_member($member_id);
            $is_own = $this->ipsclass->member['id'] == $member['id'] ? TRUE : FALSE;
            $this->output .= $this->common->load_left_content($member, $is_own, FALSE, FALSE, TRUE); 
            $this->output .= $this->ipsclass->compiled_templates['skin_bank']->start_div_content(); 
            switch ($this->ipsclass->input ['CODE']) {
                case 'exchange_fcoin' :
                        $this->show_exchange_fcoin_page ();
                        break;

                case 'transfer_fcoin' :
                        //$this->transfer_fcoin ();
                        $this->friend_transfer_fcoin();
                        break;

                case 'init_account' :
                        $this->init_bank_account ();
                        break;

                case 'transfer' :
                        $this->transfer ();
                        break;

                case 'cardinput' :
                        $this->cardinput ();
                        break;

                case 'exchange' :
                        $this->show_exchange_page ();
                        break;

                case 'exchange_process' :
                        $this->exchange_process ();
                        break;

                case 'cardpage' :
                        $this->cardpage ();
                        break;

                default :
                        $this->show_page ();
                        break;
            }
            $friends = $this->common->member_load_all_friend($this->ipsclass->member);
            $friends = $this->common->member_load_all_friend($this->ipsclass->member);
//            foreach($friends as $friend){
//                //var_dump($friend);
//                $this->ipsclass->member ['_cache'] ['friends'][$friend['id']] = 'id';
//            }
            //$this->ipsclass->member ['_cache']  = $this->common->member_load_all_friend($this->ipsclass->member);
            
            //-----------------------------------------
            // If we have any HTML to print, do so...
            //-----------------------------------------
            $this->output .= $this->ipsclass->compiled_templates['skin_bank']->end_div_content(); 
            $this->output .= $this->common->load_right_content();
            
            $this->ipsclass->print->add_output ( "$this->output" );
            $this->ipsclass->print->do_output ( array ('TITLE' => $this->page_title, 'JS' => 0, 'NAV' => $this->nav ) );
            
	}
	
	function exchange_process() {
            switch ($this->ipsclass->input ['exchange_action']) {
                case 'fcoin_enom' :
                    $this->deposit ();
                    break;

                case 'enom_fcoin' :
                    $this->get_cash ();
                    break;
            }
	}
	
	/*-------------------------------------------------------------------------*/
	// Interest processing
	/*-------------------------------------------------------------------------*/
	function interest_process($member_id = 0) {
		// Check if this is a valid member id
		if (! $member_id)
                    return;
		
		// Check if the member have account in bank
		$account = $this->check_exist_account ( $member_id );

		// Return if user have no bank account
		if (! is_array ( $account ))
                    return;
		
		// Return if account balance is less than 1
		if ($account ['balance'] < 1)
                    return;
		
		// If the interest update time have no value
		if (intval ( $account ['interest_last_update'] ) < 1) {
                    $account ['interest_last_update'] = time ();
                    $this->update_bank_account ( $account, $member_id );
                    return;
		}
		
		$total_day = floor ( (time () - $account ['interest_last_update']) / 86400 );
		// Return if day less than 1
		if ($total_day < 1)
                    return;
		
		$profit = 0;
		for($i = 1; $i <= $total_day; $i ++) {
                    $profit = $account ['balance'] * ($this->ipsclass->vars ['dkm_bank_interest'] / 100);
                    $account ['balance'] += $profit;
		}
		
		$account ['balance'] = floor ( $account ['balance'] );
		$account ['interest_last_update'] = time ();
		$this->update_bank_account ( $account, $member_id );
		
		return $account;
	}
	
	/*-------------------------------------------------------------------------*/
	// Save bank logs
	/*-------------------------------------------------------------------------*/
	function save_log($member_id = 0, $params = array(), $log = "enter_bank", $log_type = 0, $log_amount = 0, $log_balance = 0) {
		
            $logs = array ('member_id' => $member_id, 'log_type' => $log_type, 'log_message' => $this->ipsclass->lang ['log_' . $log], 'log_time' => time (), 'log_amount' => $log_amount, 'log_balance' => $log_balance );

            for($i = 0; $i < count ( $params ); $i ++) {
                $logs ['log_message'] = str_replace ( "%" . ($i + 1), $params [$i], $logs ['log_message'] );
            }

            $this->ipsclass->DB->do_insert ( 'bank_logs', $logs );
	}
	
	/*-------------------------------------------------------------------------*/
	// transfer_default_process
	// date created : 25/03/2011
	// created by : tuanhnm
	/*-------------------------------------------------------------------------*/
	function transfer_default_process() {
            $this->show_page ( $this->ipsclass->lang ['hdvnbits_not_select_systems'] );
            return;
	}
	
	/*-------------------------------------------------------------------------*/
	// transfer_maple_process
	// date created : 26/03/2011
	// updated by : tuanhnm
	// @param string $cmd   Command
        // @param array  $vars  Post variables
        // @return array	
	/*-------------------------------------------------------------------------*/
	function serverCmd($cmd, $vars=null){                   
            $curl = curl_init($cmd);

            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            //curl_setopt($curl, CURLOPT_COOKIE, "PHPSESSID=" . $this->getSessionId());	

            if (isset($vars)) {
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $vars);
            }

            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

            $body = curl_exec($curl);
            $ret = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if (curl_errno($curl) != 0) throw new Exception("SSO failure: HTTP request to server failed. " . curl_error($curl));

            return array($ret, $body);
        }
	
	/*-------------------------------------------------------------------------*/
	// transfer_maple_process
	// date created : 25/03/2011
	// created by : tuanhnm
	/*-------------------------------------------------------------------------*/
	function transfer_maple_process() {
		
            // Check if sender have account in bank
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );		

            if (! $account) {
                $this->show_page ( $this->ipsclass->lang ['account_not_created'] );
                return;
            }

            // Get transfer amount
            $amount = $this->get_amount ();

            if (! $amount) {
                $this->show_page ( $this->ipsclass->lang ['invalid_amount'] );
                return;
            }

            // Calculate transfer fee
            $transfer_fee = ceil ( $amount * $this->ipsclass->vars ['dkm_bank_transfer'] / 100 );
            $total = $amount + $transfer_fee;

            // Check user balance
            if (! $this->check_balance ( $total, $account )) {
                $this->show_page ( $this->ipsclass->lang ['not_enough_balance'] );
                return;								
            }

            if ($this->ipsclass->input ['maple_cash_type'] == 'mesos') {
                $exchanged_amount = $amount * intval ( $this->ipsclass->vars ['maple_enom_mesos'] );
            } else {
                $exchanged_amount = $amount * intval ( $this->ipsclass->vars ['maple_enom_paypalnx'] );
            }

            $client = new SoapClient ( $this->ipsclass->vars ['maple_inputcash_wsdl'], array ('soap_version' => SOAP_1_2, 'trace' => 1 ) );

            $resultCode = $client->Input ( $this->ipsclass->member ['name'], $exchanged_amount );

            if ($resultCode == 0) {
                // Update sender information
                $account ['balance'] = $account ['balance'] - $total;
                $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );

                $logs1 = array ($this->ipsclass->member ['name'], $amount, $this->ipsclass->lang ['system_maple'] );
                $this->save_log ( $this->ipsclass->member ['id'], $logs1, 'transfer_other', 6, $total, $account ['balance'] );
            } else {
                $this->show_page ( $this->ipsclass->lang ['maple_transfer_' . $resultCode] );
            }
	}
	
	/*-------------------------------------------------------------------------*/
	// Get_Error_Message_Hdvnbits
	// date created : 01/04/2011
	// created by : tuanhnm
	/*-------------------------------------------------------------------------*/
	function get_error_message_hdvnbits($key = -1)
	{
            $message_error = "";

            // Check if $key between 1 - 99 to output : general message error 
            if ($key < 100)
            {
                $message_error = $this->ipsclass->lang ['hdvnbits_error_general'];
            }
            else if ($key < 200) // Check if $key between 100 - 199 to output : user message error
            {
                $message_error = $this->ipsclass->lang ['hdvnbits_error_user'];
            }
            else if ($key < 300) // Check if $key between 200 - 299 to ouput : amount message error
            {
                $message_error = $this->ipsclass->lang ['hdvnbits_error_amount'];
            }
            else if ($key < 400) // Check if $key between 300 - 399 to ouput : log message error
            {
                $message_error = $this->ipsclass->lang ['hdvnbits_error_log'];
            }
            else // Check if $key > 400 to output : default message error;
            {
                $message_error = $this->ipsclass->lang ['hdvnbits_error_default'];
            }

            return $message_error;
	}
	
	/*-------------------------------------------------------------------------*/
	// transfer_hdvnbits_process
	// date created : 25/03/2011
	// created by : tuanhnm
	/*-------------------------------------------------------------------------*/
	function transfer_hdvnbits_process()
	{	
            // Check if sender have account in bank
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );		

            // If user not exist
            if (! $account) {
                $this->show_page ( $this->ipsclass->lang ['account_not_created'] );
                return;
            }

            // Get account hdvnbits name from account textfield 
            $acc = $this->ipsclass->input['account2'];


            // If account value is null 
            if (!isset($acc) || $acc == "")
            {
                $this->show_page ( $this->ipsclass->lang ['invalid_account'] );
                return;
            }			

            // Get money from amount textfield
            $amount = $this->get_amount ();

            // If money value isn't valid
            if (! $amount) {
                $this->show_page ( $this->ipsclass->lang ['invalid_amount'] );
                return;
            }

            // Calculate transfer fee
            $transfer_fee = ceil ( $amount * $this->ipsclass->vars ['dkm_bank_transfer'] / 100 );
            $total = $amount + $transfer_fee;

            // if total transfer fee > account balance
            if (! $this->check_balance ($total, $account )) {
                $this->show_page ( $this->ipsclass->lang ['not_enough_balance'] );
                return;
            }

            // Prepare info to transfer to hdvnbits
            $evenid = $this->ipsclass->member['id'];
            $ip = $this->ipsclass->input['IP_ADDRESS'];
            $info = array ('secretkey'=>$this->ipsclass->vars['dkm_hdvnbits_api_key'], 
                                            'evenid'=>$evenid,
                                            'username'=>$acc,
                                            'time'=>time(),
                                            'ip'=>$ip,
                                            'amount'=>$amount
                                             );

            // Call hdvnbits services			 
            $response = $this->serverCmd($this->ipsclass->vars['dkm_hdvnbits_api_url'], $info);

            // Server don't response 
            // if value != 200 response loi ket noi server hd hay gui thong tin khong day du
            // Updated by tuanhnm : remove check !$response[1]['result']
            if ($response[0] != 200 || !$response[1])
            {
                $this->show_page ( $this->ipsclass->lang ['hdvnbits_connect_error'] );
                return;
            }

            /*
             * Updated by tuanhnm on 01/04/2011
             * */
            // Get value status from server hd
            // Get string "result":111
            $message_result = strtok($response[1], ',');		
            $message_result = strtok($message_result, ':');
            // Get value of "result : 111
            $key = strtok(':');

            // Is value status isn't successfully
            if($key != 0)
            {			
                    $this->show_page ($this->get_error_message_hdvnbits($key));
                    return;
            }

            /*
             * End updated by tuanhnm
             * */

            // Update sender information
            $account ['balance'] = $account ['balance'] - $total;
            $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );


            // Set logs to systems
            $logs2 = array ($this->ipsclass->member ['name'], $amount, $this->ipsclass->lang ['system_hdvbit'], $acc, $this->ipsclass->input['IP_ADDRESS']);
            $this->save_log( $this->ipsclass->member ['id'], $logs2, 'transfer_others', 6, $amount, $account ['balance']);

            // process successfully 
            $this->show_page ( $this->ipsclass->lang ['hdvnbits_success']);	
	}
	
	/*-------------------------------------------------------------------------*/
	// Transfer to another account
	// Updated by tuanhnm on 30/3/2011
	/*-------------------------------------------------------------------------*/
	function transfer() {
            // Check if sender have account in bank
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );		

            if (! $account) {
                    $this->show_page ( $this->ipsclass->lang ['account_not_created'] );
                    return;
            }

            if ($this->ipsclass->input ['transfer_to'] == 'friend') {
                $this->friend_transfer ( $account );
            } else {

                // Get type other_system 
                $choice_system = $this->ipsclass->input['other_system'];

                // Switch option to select system 
                switch ($choice_system) {
                    case 1:			
                        $this->transfer_maple_process();							
                        break;
                    case 2:
                        $this->transfer_hdvnbits_process();
                        break;				
                    default:
                        $this->transfer_default_process();
                        break;
                }
            //$this->ipsclass->DB->do_update( 'members', array( 'maple_check' => 0 ), 'id='.$member['id'] );
            }

            //$this->show_page ( $this->ipsclass->lang ['transfer_success'] );
	}
		
	
	function friend_transfer_fcoin() {
		
            // Check if receiver is member of forum
            if ($this->ipsclass->input ['friend_name'])
                    $this->ipsclass->input ['account'] = $this->ipsclass->input ['friend_name'];

            $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'members', 'where' => 'name=\'' . $this->ipsclass->input ['account'] . '\'' ) );
            $this->ipsclass->DB->simple_exec ();
            if (! $result = $this->ipsclass->DB->fetch_row ()) {
                    $this->show_exchange_fcoin_page ( $this->ipsclass->lang ['invalid_member'] );
                    return;
            }

            // Get transfer amount
            $amount = $this->get_amount ();
            if (! $amount) {
                    $this->show_exchange_fcoin_page ( $this->ipsclass->lang ['invalid_amount'] );
                    return;
            }

            // Calculate transfer fee
            $transfer_fee = ceil ( $amount * $this->ipsclass->vars ['dkm_bank_transfer'] / 100 );
            $total = $amount + $transfer_fee;

            // Check user balance
            if (! $this->check_cash($total)) {
                    $this->show_exchange_fcoin_page ( $this->ipsclass->lang ['fcoin_transfer_not_enough'] );
                    return;
            }

            // Update sender information
            $sender_fcoin = $this->ipsclass->member[$this->cash_field]-$total;
            $this->update_member_account ( $sender_fcoin, $this->ipsclass->member ['id'] );
            $this->ipsclass->member[$this->cash_field] = $sender_fcoin;

            $logs1 = array ($this->ipsclass->member ['name'], $amount, $result ['name'] );
            $this->save_log ( $this->ipsclass->member ['id'], $logs1, 'fcoin_send', 7, $total, $sender_fcoin );

            // Update receiver information
            $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'pfields_content', 'where' => 'member_id=' . $result['id'] ) );
            $this->ipsclass->DB->simple_exec ();
            $receiver_account = $this->ipsclass->DB->fetch_row();

            $receiver_fcoin = $receiver_account [$this->cash_field] + $amount;
            $this->update_member_account ( $receiver_fcoin, $result['id'] );

            $logs2 = array ($result ['name'], $amount, $this->ipsclass->member ['name'] );

            $this->save_log ( $receiver_account ['member_id'], $logs2, 'fcoin_receive', 8, $amount, $receiver_fcoin );

            $this->show_exchange_fcoin_page ( $this->ipsclass->lang ['fcoin_transfer_success'] );
	}
	
	/*
	 * Updated question by tuanhnm on 31/03/2011
	 * 
	 * if user send mine ??s
	 * */
	function friend_transfer($account = array()) {
            // Check if receiver is member of forum
            if ($this->ipsclass->input ['friend_name'])
                    $this->ipsclass->input ['account'] = $this->ipsclass->input ['friend_name'];

            $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'members', 'where' => 'name=\'' . $this->ipsclass->input ['account'] . '\'' ) );
            $this->ipsclass->DB->simple_exec ();
            if (! $result = $this->ipsclass->DB->fetch_row ()) {
                    $this->show_page ( $this->ipsclass->lang ['invalid_member'] );
                    return;
            }

            // Check if receiver have account in bank
            // First update the interest of receiver
            $this->interest_process ( $result ['id'] );

            $receiver = $this->check_exist_account ( $result ['id'] );
            if (! $receiver) {
                    $this->show_page ( $this->ipsclass->lang ['receiver_not_created'] );
                    return;
            }

            // Get transfer amount
            $amount = $this->get_amount ();
            if (! $amount) {
                    $this->show_page ( $this->ipsclass->lang ['invalid_amount'] );
                    return;
            }

            // Calculate transfer fee
            $transfer_fee = ceil ( $amount * $this->ipsclass->vars ['dkm_bank_transfer'] / 100 );
            $total = $amount + $transfer_fee;

            // Check user balance
            if (! $this->check_balance ( $total, $account )) {
                    $this->show_page ( $this->ipsclass->lang ['not_enough_balance'] );
                    return;
            }

            // Update sender information
            $account ['balance'] = $account ['balance'] - $total;
            $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );

            $logs1 = array ($this->ipsclass->member ['name'], $amount, $result ['name'] );
            $this->save_log ( $this->ipsclass->member ['id'], $logs1, 'transfer_send', 3, $total, $account ['balance'] );

            // Update receiver information
            $receiver ['balance'] = $receiver ['balance'] + $amount;
            $this->update_bank_account ( $receiver, $result ['id'] );

            $logs2 = array ($result ['name'], $amount, $this->ipsclass->member ['name'], $amount, $receiver ['balance'] );

            $this->save_log ( $receiver ['member_id'], $logs2, 'transfer_receive', 4 );
	}
	
	/*-------------------------------------------------------------------------*/
	// Get cash
	/*-------------------------------------------------------------------------*/
	function get_cash() {
		
            // Check if account is exist
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );
            if (! $account) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['account_not_created'] );
                    return;
            }

            // Getting safe amount
            $amount = $this->get_amount ();
            if (! $amount) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['invalid_amount'] );
                    return;
            }

            if (($amount % 100) != 0) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['exchange_fcoin_input_error'] );
                    return;
            }

            $enom = $amount * $this->ipsclass->vars ['bank_exchange_enom_fcoin_enom'] / $this->ipsclass->vars ['bank_exchange_enom_fcoin_fcoin'];

            // Check user balance
            if (! $this->check_balance ( $enom, $account )) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['not_enough_balance'] );
                    return;
            }

            $config = $this->configs ['available_fcoin'];
            if ($config ['bank_config_value'] < $amount) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['exchange_not_enough_available_fcoin'] );
                    return;
            }

            $config ['bank_config_value'] = $config ['bank_config_value'] - $amount;
            $this->ipsclass->DB->do_update ( 'bank_configs', $config, "bank_config_id=" . $config ['bank_config_id'] );
            $this->configs ['available_fcoin'] = $config;

            // Update information
            $account ['balance'] = $account ['balance'] - $enom;
            $cash = $this->ipsclass->member [$this->cash_field] + $amount;
            $this->ipsclass->member [$this->cash_field] = $cash;

            $this->update_member_account ( $cash, $this->ipsclass->member ['id'] );
            $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );

            $logs = array ($this->ipsclass->member ['name'], $amount );
            $this->save_log ( $this->ipsclass->member ['id'], $logs, 'get_cash', 2, $amount, $account ['balance'] );

            $this->show_exchange_page ( $this->ipsclass->lang ['get_cash_success'] );
	}
	
	/*
	 * Updated by tuanhnm on date 30/3/2011
	 * 
	 * */
	/*-------------------------------------------------------------------------*/
	// Card Input
	/*-------------------------------------------------------------------------*/
	function cardinput() {
            if (! isset ( $_SESSION )) {
                session_start ();
                if (! isset ( $_SESSION ['error_count'] ))
                    $_SESSION ['error_count'] = 0;
            }
            // Check if account is exist
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );
            if (! $account) {
                $this->cardpage ( $this->ipsclass->lang ['account_not_created'] );
                return;
            }
            if ($_SESSION ['error_count'] >= 3) {
                //-----------------------------------------
                // Anti bot flood...
                //-----------------------------------------
                if ($this->ipsclass->vars ['bot_antispam']) {
                    //-----------------------------------------
                    // Check the security code:
                    //-----------------------------------------
                    if ($this->ipsclass->input ['regid'] == "") {
                        $this->cardpage ( $this->ipsclass->lang ['err_security_code'] );
                        return "";
                    }

                    $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'reg_antispam', 'where' => "regid='" . trim ( $this->ipsclass->txt_alphanumerical_clean ( $this->ipsclass->input ['regid'] ) ) . "'" ) );

                    $this->ipsclass->DB->simple_exec ();

                    if (! $row = $this->ipsclass->DB->fetch_row ()) {
                        $this->cardpage ( $this->ipsclass->lang ['err_security_code'] );
                        return "";
                    }

                    if (trim ( $this->ipsclass->txt_alphanumerical_clean ( $this->ipsclass->input ['reg_code'] ) ) != $row ['regcode']) {
                        $this->cardpage ( $this->ipsclass->lang ['err_security_code'] );
                        return "";
                    }

                    $this->ipsclass->DB->do_delete ( 'reg_antispam', "regid='" . trim ( $this->ipsclass->txt_alphanumerical_clean ( $this->ipsclass->input ['regid'] ) ) . "'" );
                }
            }
            /*
             * Updated by tuanhnm on date 30/3/2011, on date 31/3/2011
             *  BEGIN VALIDATE ACCOUNT_HD FIELD
             * */

         // Get select require from user by get value of 'select_option' select tag
         $select_transfer = $this->ipsclass->input['other_action'];

         // Check if user require transfer money to hdvnbits.org
         if ($select_transfer == 1)
         {
             // Get account information from 'account_hd' field
             $this->acc_hdvnbit = $this->ipsclass->input['account_hd'];

             // Check if $acc_hdvnbit is null/
             if (!isset($this->acc_hdvnbit) || $this->acc_hdvnbit == "")
             {
                 // Increment $_SESSION ['error_count'] ;
                 $_SESSION ['error_count'] ++;
                /*
                         * updated by hnmtuan on 05/04/2011
                         * */
                 $this->is_hdvnbit_select = false;
                 $message = $this->ipsclass->lang ['gate_transfer_hdvnbit_acc_null'];
                 $this->cardpage ( $message);
                 return;
             }

             // Change state $is_hdvnbit_select to 'true' to give information system hdvnbit is selected
             $this->is_hdvnbit_select = true;

         }

         // Check if user require transfer money to maple server ** Updated 31/3/2011
         if ($select_transfer == 2)
         {
             // Check if sender have account in bank
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );		

            // Check if account not exists
            if (! $account) {
                // Increment $_SESSION ['error_count'] ;
                $_SESSION ['error_count'] ++;
                /*
                 * updated by hnmtuan on 05/04/2011
                 * */
                 $this->is_maple_select = false;
                $this->cardpage ( $this->ipsclass->lang ['account_not_created'] );
                return;
            }

             // Change state $is_maple_select to 'true' to give information system maple is selected			 
             $this->is_maple_select = true;
         }

         /*
          * Updated by tuanhnm
          * END VALIDATE ACCOUNT_HD FIELD
          * */

        require_once (KERNEL_PATH . 'nusoap/nusoap.php');

        $client = new nusoap_client ( $this->ipsclass->vars ['gate_service_url'], 'wsdl' );
        $err = $client->getError ();
        if ($err) {
                $this->cardpage ( $this->ipsclass->lang ['err_web_service'] );
                return;
        }

        // Doc/lit parameters get wrapped
        $UserName = $this->ipsclass->member ['name'];
        $Serial = $this->ipsclass->input ['card_seri'];
        $PIN = $this->ipsclass->input ['card_pin'];
        $PartnerID = $this->ipsclass->vars ['gate_partner_id'] ? $this->ipsclass->vars ['gate_partner_id'] : "46";
        $Signature = "";

        //Begin digital sign
        $OriginalData = $UserName . $Serial . $PartnerID . $PIN;

        $tmp_path = tempnam ( "/home/httpdocs/php/account/tmp/", 'pem' );
        file_put_contents ( $tmp_path . '_data.txt', $OriginalData );
        $clearFile = $tmp_path . '_data.txt';
        $signedFile = $tmp_path . '_signed.txt';
        $public_key = ROOT_PATH . "sources/components_public/gateservices/server.crt";
        $private_key = ROOT_PATH . "sources/components_public/gateservices/server.key";
        if (openssl_pkcs7_sign( $clearFile, $signedFile, file_get_contents ( $public_key ), array (file_get_contents ( $private_key ), "123456" ), array () )) {
            $signedData = explode ( "\n\n", file_get_contents ( $signedFile ) );
            @unlink ( $tmp_path );
            @unlink ( $clearFile );
            @unlink ( $signedFile );
            $Signature = $signedData [3];
        }
        //End digital sign


        // Updated by tuanhnm : Call wsdl from FPT gate and check account by response result
        $param = array ('UserName' => $UserName, 'Serial' => $Serial, 'PIN' => $PIN, 'PartnerID' => $PartnerID, 'ClientIP' => $this->ipsclass->input ['IP_ADDRESS'], 'Signature' => $Signature );
        $result = $client->call ( 'CardInput', $param, '', '', false, true );


            if ($client->fault) {
                $this->cardpage ( "Error." );
                return;
            }

            // Check for errors
            $err = $client->getError ();


            if ($err) {
                // Display the error
                $this->cardpage ( $err );
                return;
            }

            if ($result ["CardInputResult"] ["anyType"] [0] == - 1) {
                $_SESSION ['error_count'] ++;
                $this->cardpage ( $result ["CardInputResult"] ["anyType"] [1] );
                return;
            }

            /*
             * Updated by tuanhnm
             *  Lay thong so tien trong the dong thoi 
             *  Theo nghi thi dung la $amount = $card_amount + $card_amount*$this->ipsclass->vars ['cardinput_rate'] / 100
             * vd nap the 20.000 VND
             * $amount = 20.000 + 20.000*2/100 = 20.000 + 400 = 20.400 VND
             * */	

            // Calculate amount
            $card_amount = $result ["CardInputResult"] ["anyType"] [2];
            $amount = $card_amount * $this->ipsclass->vars ['cardinput_rate'] / 100;

            // Update information
            $account ['balance'] = $account ['balance'] + $amount;
            $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );

            /*
             * Updated by tuanhnm : save log when input card successfully with form "%1 nạp thẻ thành công với số seri %2 và PIN %3"
             * 
             * */
            $logs = array ($this->ipsclass->member ['name'], $Serial, $PIN );
            $this->save_log ( $this->ipsclass->member ['id'], $logs, 'cardinput', 5, $amount, $account ['balance'] );

            $message = $result ["CardInputResult"] ["anyType"] [1] . ".";
            $message .= sprintf ( $this->ipsclass->lang ['card_amount'], $result ["CardInputResult"] ["anyType"] [2] );
            $message .= sprintf ( $this->ipsclass->lang ['card_balance'], $account ['balance'] );			

            /*
             * Updated by tuanhnm
             * 
             * BEGIN COMPONENTS
             * transfer money to hdvnbits system
             * 
             * */

             // Check if hdvnbits system is selected and validated successfully by pass $is_hdvnbit_select
             if ($this->is_hdvnbit_select)
             {

                // Calculate transfer fee before transfer
                $transfer_fee = ceil ( $amount * $this->ipsclass->vars ['dkm_bank_transfer'] / 100 );
                $total = $amount + $transfer_fee;

                // Check if total transfer fee > asccount balance
                if (! $this->check_balance ($total, $account )) {
                        $this->cardpage ( $this->ipsclass->lang ['not_enough_balance'] );
                        return;
                }

                    /* 
                     // Prepare infomation to transfer hdvnbits.org ******
                     // Is amount $card_amount or $amount
                    $info = array ('secretkey'=>$this->ipsclass->vars['dkm_hdvnbits_api_key'], 
                                                     'username'=>$this->acc_hdvnbit,
                                                     'amount'=>$amount //****
                                                     );		*/
                // Updated by tuanhnm on 01/04/2010				 
                // Prepare info to transfer to hdvnbits
                $evenid = $this->ipsclass->member['id'];
                $ip = $this->ipsclass->input['IP_ADDRESS'];
                $info = array ('secretkey'=>$this->ipsclass->vars['dkm_hdvnbits_api_key'], 
                                                'evenid'=>$evenid,
                                                'username'=>$this->acc_hdvnbit,
                                                'time'=>time(),
                                                'ip'=>$ip,
                                                'amount'=>$amount
                                                 );

                // Send $info to services of hdvnbits.org 
                $result = $this->serverCmd($this->ipsclass->vars['dkm_hdvnbits_api_url'], $info);

                // Check if services of hdvnbits.org don't actived or send information enough ****
                // Updated by tuanhnm : remove check !$response[1]['result']
                // Changed response to result
                if ($result[0] != 200 || !$result[1])
                {
                        $this->is_hdvnbit_select = false;
                        $this->cardpage( $this->ipsclass->lang ['hdvnbits_connect_error'] );				
                        return;
                }

                /*
                 * Updated by tuanhnm on 01/04/2011
                 * */
                // Get value status from server hd
                // Get string "result":111
                $message_result = strtok($result[1], ',');		
                $message_result = strtok($message_result, ':');
                // Get value of "result : 111
                $key = strtok(':');

                // Is value status isn't successfully
                if($key != 0)
                {			
                    $this->is_hdvnbit_select = false;
                    $this->show_page ($this->get_error_message_hdvnbits($key));			
                    return;
                }

                /*
                 * End updated by tuanhnm
                 * */

                /* Updated by tuanhnm : comment old on 31/3/2011
                // Get information is responsed from hdvnbits.orgs systems
                $key = $response[1]['result'];

                // Check if transfer money don't successfully because invalid account information or input money
                // $key = 5 : input money is invalid
                if ($key != 0)
                {
                        $this->cardpage( $this->ipsclass->lang ['hdvnbits_error_'.$key] );
                        return;
                }*/

                // Update sender information
                $account ['balance'] = $account ['balance'] - $total;
                $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );


                // Set logs to systems 
                // Co can luu so tien chuyen cho tai khoan kia $amount hay tong chi phi $total ?****	
                // 	Time : tu dong luu
                //  ip user : 'ClientIP' => $this->ipsclass->input ['IP_ADDRESS']
                // usereven : 
                $logs2 = array ($this->ipsclass->member ['name'], $amount, $this->ipsclass->lang ['system_hdvbit'], $acc, $this->ipsclass->input['IP_ADDRESS']);
                $this->save_log( $this->ipsclass->member ['id'], $logs2, 'FPT_transfer_hdvnbits', 6, $amount, $account ['balance']);

                // Co can luu thong tin chuyen tien qua tai khoan hdvnbits thanh cong hay khong ? ***
                $message = $this->ipsclass->lang ['hdvnbits_success'];			

            }

             // Updated by tuanhnm on 31/3/2011
             // Check if user select transfer money to maple servers
             if ($this->is_maple_select)
             {							

                // Calculate transfer fee
                $transfer_fee = ceil ( $amount * $this->ipsclass->vars ['dkm_bank_transfer'] / 100 );
                $total = $amount + $transfer_fee;

                // Check user balance
                if (! $this->check_balance ( $total, $account )) {
                        $this->is_maple_select = false;
                        $this->cardpage ( $this->ipsclass->lang ['not_enough_balance'] );

                        return;								
                }

                if ($this->ipsclass->input ['maple_cash_type'] == 'mesos') {
                    $exchanged_amount = $amount * intval ( $this->ipsclass->vars ['maple_enom_mesos'] );
                } else {
                    $exchanged_amount = $amount * intval ( $this->ipsclass->vars ['maple_enom_paypalnx'] );
                }

                $client = new SoapClient ( $this->ipsclass->vars ['maple_inputcash_wsdl'], array ('soap_version' => SOAP_1_2, 'trace' => 1 ) );

                $resultCode = $client->Input ( $this->ipsclass->member ['name'], $exchanged_amount );

                if ($resultCode == 0) {
                    // Update sender information
                    $account ['balance'] = $account ['balance'] - $total;
                    $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );

                    $logs1 = array ($this->ipsclass->member ['name'], $amount, $this->ipsclass->lang ['system_maple'] );
                    $this->save_log ( $this->ipsclass->member ['id'], $logs1, 'transfer_other', 6, $total, $account ['balance'] );
                } else {
                    $message =  $this->ipsclass->lang ['maple_transfer_' . $resultCode];
                }
             }

            /*
             * Updated by tuanhnm
             * 
             * END COMPONENTS
             * transfer money to hdvnbits system
             * */

            /*
              * Updated by tuanhnm on 31/03/2011
              * */
            // After processing resign is_hdvnbit_select = false, is_maple_select = false
            $this->is_hdvnbit_select = false;
            $this->is_maple_select = false;

            $this->cardpage ($message);
	}
	
	/*-------------------------------------------------------------------------*/
	// Deposit
	/*-------------------------------------------------------------------------*/
	function deposit() {
		
            // Check if account is exist
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );
            if (! $account) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['account_not_created'] );
                    return;
            }

            $amount = $this->get_amount ();
            if (! $amount) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['invalid_amount'] );
                    return;
            }

            if (($amount % 10) != 0) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['exchange_enom_input_error'] );
                    return;
            }

            $fcoin = $amount * ($this->ipsclass->vars ['bank_exchange_fcoin_enom_fcoin']) / ($this->ipsclass->vars ['bank_exchange_fcoin_enom_enom']);

            if (! $this->check_cash ( $fcoin )) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['not_enough_cash'] );
                    return;
            }

            $config = $this->configs ['available_enom'];
            if ($config ['bank_config_value'] < $amount) {
                    $this->show_exchange_page ( $this->ipsclass->lang ['exchange_not_enough_available_enom'] );
                    return;
            }

            $config ['bank_config_value'] = $config ['bank_config_value'] - $amount;
            $this->ipsclass->DB->do_update ( 'bank_configs', $config, "bank_config_id=" . $config ['bank_config_id'] );
            $this->configs ['available_enom'] = $config;

            // Update information
            $account ['balance'] = $account ['balance'] + $amount;

            $cash = $this->ipsclass->member [$this->cash_field] - $fcoin;
            $this->ipsclass->member [$this->cash_field] = $cash;

            $this->update_member_account ( $cash, $this->ipsclass->member ['id'] );
            $this->update_bank_account ( $account, $this->ipsclass->member ['id'] );

            $logs = array ($this->ipsclass->member ['name'], $amount );
            $this->save_log ( $this->ipsclass->member ['id'], $logs, 'deposit', 1, $amount, $account ['balance'] );

            $this->show_exchange_page ( $this->ipsclass->lang ['deposit_success'] );
	}
	
	/*-------------------------------------------------------------------------*/
	// Init bank account process
	/*-------------------------------------------------------------------------*/
	function init_bank_account() {
		
		// First check if the account have been created
		$account = $this->check_exist_account ( $this->ipsclass->member ['id'] );
		if (is_array ( $account )) {
			$this->show_page ( $this->ipsclass->lang ['init_already_exist'] );
			return;
		}
		
		$account_info = array ('member_id' => $this->ipsclass->member ['id'], 'balance' => 0, 'init_time' => time () );
		
		$this->ipsclass->DB->do_insert ( 'bank_accounts', $account_info );
		
		$this->save_log ( $this->ipsclass->member ['id'], array ($this->ipsclass->member ['name'] ), 'init_account', 0 );
		
		$this->show_page ( $this->ipsclass->lang ['init_success'] );
	}
	
	/*-------------------------------------------------------------------------*/
	// Show card page
	/*-------------------------------------------------------------------------*/
	function cardpage($message = "") {
		$account = $this->check_exist_account ( $this->ipsclass->member ['id'] );
		$html = array ();
		$html ['message'] = $message;
		if (is_array ( $account ) && count ( $account )) {
                    // Update the interest for owner
                    $this->interest_process ( $this->ipsclass->member ['id'] );
                    $account ['init_time'] = $this->ipsclass->get_date ( $account ['init_time'], 'DATE' );
                    $account ['account_name'] = $this->ipsclass->member ['name'];
                    $html ['account_stats'] = $this->ipsclass->compiled_templates ['skin_bank']->account_stats ( $account );
                    if (! isset ( $_SESSION )) {
                        session_start ();
                        if (! isset ( $_SESSION ['error_count'] ))
                            $_SESSION ['error_count'] = 0;
                    }
                    /// erro_count ??, card_seri, va card_pin kiem tra va lay du lieu o dau, sau khi ktra the xong lay so tien trong the nhu the nao,?
                    if ($_SESSION ['error_count'] >= 3) {
                        // Show captcha for security
                        if ($this->ipsclass->vars ['bot_antispam']) {
                            //-----------------------------------------
                            // Set up security code
                            //-----------------------------------------
                            // Set a new ID for this reg request...
                            $regid = md5 ( uniqid ( microtime () ) );
                            if ($this->ipsclass->vars ['bot_antispam'] == 'gd') {
                                //-----------------------------------------
                                // Get 6 random chars
                                //-----------------------------------------						
                                $reg_code = strtoupper ( substr ( md5 ( mt_rand () ), 0, 6 ) );
                            } else {
                                //-----------------------------------------
                                // Set a new 6 character numerical string
                                //-----------------------------------------
                                $reg_code = mt_rand ( 100000, 999999 );
                            }
                            // insert cai gi vo database ??
                            // Insert into the DB
                            $this->ipsclass->DB->do_insert ( 'reg_antispam', array ('regid' => $regid, 'regcode' => $reg_code, 'ip_address' => $this->ipsclass->input ['IP_ADDRESS'], 'ctime' => time () ) );
                            if ($this->ipsclass->vars ['bot_antispam'] == 'gd') {
                                $html ['antibot'] = $this->ipsclass->compiled_templates ['skin_bank']->captcha_gd ( $regid );
                            } else {
                                $html ['antibot'] = $this->ipsclass->compiled_templates ['skin_bank']->captcha_img ( $regid );
                            }	
                            $html['gate_card_extra_ad'] = $this->ipsclass->compiled_templates['skin_bank']->gate_card_extra_ads();
                        }
                    }
                    // Display logs
                    $log_types = array (5 );// FPT Gate card log
                    // ket qua cua truy van nay dau ?
                    $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'bank_logs', 'where' => 'log_type IN(' . implode ( ",", $log_types ) . ') AND member_id=' . intval ( $this->ipsclass->member ['id'] ), 'order' => 'log_time DESC', 'limit' => array (0, 12 ) ) );
                    $this->ipsclass->DB->simple_exec ();
                    $count = 1;
                    $html ['logs'] = "";
                    while ( $log_item = $this->ipsclass->DB->fetch_row () ) {
                        $log_item ['log_count'] = $count;
                        $log_item ['log_css'] = ($count % 2) + 1;
                        $log_item ['log_time'] = $this->ipsclass->get_date ( $log_item ['log_time'], get_date );
                        $html ['logs'] .= $this->ipsclass->compiled_templates ['skin_bank']->log_row ( $log_item );
                        $count ++;
                    }
                $this->output .= $this->ipsclass->compiled_templates ['skin_bank']->bank_cardpage ( $html );
            } else {
                $this->output .= $this->ipsclass->compiled_templates ['skin_bank']->no_account_page ( $html );
            }
            $this->save_log ( $this->ipsclass->member ['id'], array ($this->ipsclass->member ['name'] ) );
            $this->page_title = $this->ipsclass->lang ['page_title'];
            //$this->nav        = array( $this->ipsclass->lang['page_title'] );
	}
	
	/*-------------------------------------------------------------------------*/
	// Show exchange page
	/*-------------------------------------------------------------------------*/
	function show_exchange_page($message = "") {
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );
            $html = array ();
            $html ['message'] = $message;
            if (is_array ( $account ) && count ( $account )) {
                // Update the interest for owner
                $this->interest_process ( $this->ipsclass->member ['id'] );
                $account ['init_time'] = $this->ipsclass->get_date ( $account ['init_time'], 'DATE' );
                $account ['account_name'] = $this->ipsclass->member ['name'];
                $account ['fcoin'] = $this->ipsclass->member [$this->cash_field];
                $html ['account_stats'] = $this->ipsclass->compiled_templates ['skin_bank']->account_stats_exchange ( $account );
                // Display logs
                $log_types = array (1, // Deposit from cash to Even bank account
                                    2 // Withdraw from Even bank account to cash 
                                    );
                $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'bank_logs', 'where' => 'log_type IN(' . implode ( ",", $log_types ) . ') AND member_id=' . intval ( $this->ipsclass->member ['id'] ), 'order' => 'log_time DESC', 'limit' => array (0, 12 ) ) );
                $this->ipsclass->DB->simple_exec ();
                $count = 1;
                $html ['logs'] = "";
                while ( $log_item = $this->ipsclass->DB->fetch_row () ) {
                    $log_item ['log_count'] = $count;
                    $log_item ['log_css'] = ($count % 2) + 1;
                    $log_item ['log_time'] = $this->ipsclass->get_date ( $log_item ['log_time'], 'DATE' );
                    $html ['logs'] .= $this->ipsclass->compiled_templates ['skin_bank']->log_row ( $log_item );
                    $count ++;
                }
                $html ['available_enom'] = number_format ( $this->configs ['available_enom'] ['bank_config_value'] );
                $html ['available_fcoin'] = number_format ( $this->configs ['available_fcoin'] ['bank_config_value'] );
                $this->output .= $this->ipsclass->compiled_templates ['skin_bank']->bank_exchange_page ( $html );
            } else {
                $this->output .= $this->ipsclass->compiled_templates ['skin_bank']->no_account_page ( $html );
            }
            $this->save_log ( $this->ipsclass->member ['id'], array ($this->ipsclass->member ['name'] ) );
            $this->page_title = $this->ipsclass->lang ['page_title'];
            //$this->nav        = array( $this->ipsclass->lang['page_title'] );
	}
	
	/*-------------------------------------------------------------------------*/
	// Show exchange fcoin page
	/*-------------------------------------------------------------------------*/
	function show_exchange_fcoin_page($message = "") {
            $html = array ();
            $html ['message'] = $message;
            // Update the interest for owner
            $account ['init_time'] = $this->ipsclass->get_date ( $this->ipsclass->member ['joined'], 'DATE' );
            $account ['account_name'] = $this->ipsclass->member ['name'];
            $account ['balance'] = $this->ipsclass->member [$this->cash_field];
            $html ['account_stats'] = $this->ipsclass->compiled_templates ['skin_bank']->account_stats_fcoin ( $account );
            // Display logs
            $log_types = array (7, // Transfer fcoin
                                8  // receive fcoin from other
                                );

            $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'bank_logs', 'where' => 'log_type IN(' . implode ( ",", $log_types ) . ') AND member_id=' . intval ( $this->ipsclass->member ['id'] ), 'order' => 'log_time DESC', 'limit' => array (0, 12 ) ) );
            $this->ipsclass->DB->simple_exec ();
            $count = 1;
            $html ['logs'] = "";
            while ( $log_item = $this->ipsclass->DB->fetch_row () ) {
                $log_item ['log_count'] = $count;
                $log_item ['log_css'] = ($count % 2) + 1;
                $log_item ['log_time'] = $this->ipsclass->get_date ( $log_item ['log_time'], 'DATE' );
                $html ['logs'] .= $this->ipsclass->compiled_templates ['skin_bank']->log_row ( $log_item );
                $count ++;
            }
            $friends = $this->common->member_load_all_friend($this->ipsclass->member);
            foreach($friends as $friend){
                //var_dump($friend);
                $this->ipsclass->member ['_cache'] ['friends'][$friend['id']] = 'id';
            }
            // Get friend list
            $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'members', 'where' => 'id IN(' . trim ( '0,' . implode ( ',', array_keys ( $this->ipsclass->member ['_cache'] ['friends'] ) ), "," ) . ')', 'order' => 'name DESC' ) );
            $this->ipsclass->DB->simple_exec ();
            $html ['friends'] = "";
            while ( $friend = $this->ipsclass->DB->fetch_row () ) {
                    $html ['friends'] .= $this->ipsclass->compiled_templates ['skin_bank']->friend_option ( $friend );
            }
            $this->output .= $this->ipsclass->compiled_templates ['skin_bank']->bank_fcoin_page ( $html );
            $this->save_log ( $this->ipsclass->member ['id'], array ($this->ipsclass->member ['name'] ) );
            $this->page_title = $this->ipsclass->lang ['page_title'];
            //$this->nav        = array( $this->ipsclass->lang['page_title'] );
	}
	
	/*-------------------------------------------------------------------------*/
	// Show bank page
	/*-------------------------------------------------------------------------*/
	function show_page($message = "") {
            $account = $this->check_exist_account ( $this->ipsclass->member ['id'] );
            $html = array ();
            $html ['message'] = $message;
            if (is_array ( $account ) && count ( $account )) {
                // Update the interest for owner
                $this->interest_process ( $this->ipsclass->member ['id'] );
                $account ['init_time'] = $this->ipsclass->get_date ( $account ['init_time'], 'DATE' );
                $account ['account_name'] = $this->ipsclass->member ['name'];
                $html ['account_stats'] = $this->ipsclass->compiled_templates ['skin_bank']->account_stats ( $account );
                // Display logs
                $log_types =array (
                    3, // Transfer evenom
                    4, // receive evenom from other
                    6 
                )// Transfer enom to other system
                ;
                $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'bank_logs', 'where' => 'log_type IN(' . implode ( ",", $log_types ) . ') AND member_id=' . intval ( $this->ipsclass->member ['id'] ), 'order' => 'log_time DESC', 'limit' => array (0, 12 ) ) );
                $this->ipsclass->DB->simple_exec ();
                $count = 1;
                $html ['logs'] = "";
                while ( $log_item = $this->ipsclass->DB->fetch_row () ) {
                    //print_r($log_item);exit();
                    $log_item ['log_count'] = $count;
                    $log_item ['log_css'] = ($count % 2) + 1;
                    $log_item ['log_time'] = $this->ipsclass->get_date ( $log_item ['log_time'] ,'SHORT');
                    $html ['logs'] .= $this->ipsclass->compiled_templates ['skin_bank']->log_row ( $log_item );
                    $count ++;
                }
                $friends = $this->common->member_load_all_friend($this->ipsclass->member);
                foreach($friends as $friend){
                    //var_dump($friend);
                    $this->ipsclass->member ['_cache'] ['friends'][$friend['id']] = 'id';
                }
//                var_dump($this->ipsclass->member ['_cache'] ['friends']);
//                exit(); 
                // Get friend list
                $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'members as m', 'where' => 'm.id IN(' . trim ( '0,' . implode ( ',', array_keys ( $this->ipsclass->member ['_cache'] ['friends'] ) ), "," ) . ')', 'order' => 'name DESC' ) );
                $this->ipsclass->DB->simple_exec ();
                $html ['friends'] = "";
                while ( $friend = $this->ipsclass->DB->fetch_row () ) {
                    //var_dump($friend);
                        $html ['friends'] .= $this->ipsclass->compiled_templates ['skin_bank']->friend_option ( $friend );
                }
                //echo $html ['friends'];exit();
                // Get other system list
                $html ['systems'] = "";
                foreach ( $this->system_config as $key => $value ) {				
                    if ($value['enable']){		
                        //$html ['systems'] .= $this->ipsclass->compiled_templates ['skin_bank']->system_option ( $value["key"] );
                    }
                    if($value['extra_html']) {
                        //$html ['extra_html'] .= $this->ipsclass->compiled_templates ['skin_bank']->$value ["extra_html"]();
                    }
                }						
                $this->output .= $this->ipsclass->compiled_templates ['skin_bank']->bank_page ( $html );
            } else {
                    $this->output .= $this->ipsclass->compiled_templates ['skin_bank']->no_account_page ( $html );
            }
            $this->save_log ( $this->ipsclass->member ['id'], array ($this->ipsclass->member ['name'] ) );
            $this->page_title = $this->ipsclass->lang ['page_title'];
            //$this->nav        = array( $this->ipsclass->lang['page_title'] );
	}
	
	/*-------------------------------------------------------------------------*/
	// Update member account
	/*-------------------------------------------------------------------------*/
	function update_member_account($cash = 0, $account_id = 0) {
            $info = array ($this->cash_field => $cash );
            $this->ipsclass->DB->do_update ( 'pfields_content', $info, 'member_id=' . $account_id );
	}
	
	/*-------------------------------------------------------------------------*/
	// Update bank account
	/*-------------------------------------------------------------------------*/
	function update_bank_account($info = array(), $account_id = 0) {
            $this->ipsclass->DB->do_update ( 'bank_accounts', $info, 'member_id=' . $account_id );
	}
	
	/*-------------------------------------------------------------------------*/
	// Check if amount is valid and get it
	/*-------------------------------------------------------------------------*/
	function get_amount() {
            // Make sure the input is number and greater than 0
            $amount = intval ( $this->ipsclass->input ['amount'] ) > 0 ? $this->ipsclass->input ['amount'] : 0;
            // If input amount is invalid redirect to main page
            if (! $amount) {
                return false;
            }
            return $amount;
	}
	
	/*-------------------------------------------------------------------------*/
	// Check if user have enough balance
	/*-------------------------------------------------------------------------*/
	function check_balance($amount = 0, $account = array()) {
            if ($account ['balance'] < $amount)
                return false;
            return true;
	}
	
	/*-------------------------------------------------------------------------*/
	// Check if user have enough cash
	/*-------------------------------------------------------------------------*/
	function check_cash($amount = 0) {
            if ($this->ipsclass->member [$this->cash_field] < $amount)
                return false;
            return true;
	}
	
	/*-------------------------------------------------------------------------*/
	// Check if account exist
	/*-------------------------------------------------------------------------*/
	function check_exist_account($value = "") {
            $this->ipsclass->DB->simple_construct ( array ('select' => '*', 'from' => 'bank_accounts', 'where' => 'member_id=' . $value ) );
            $this->ipsclass->DB->simple_exec ();
            if (! $account = $this->ipsclass->DB->fetch_row ()) {
                return false;
            }
            return $account;
	}
}

?>
